package com.by.server.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by.server.mapper.MenuMapper;
import com.by.server.pojo.Admin;
import com.by.server.pojo.Menu;
import com.by.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yufei
 * @since 2021-11-04
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 根据用户id获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getAdminByUserId() {
        Integer adminId = ((Admin) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal()).getId();
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 从redis中获取数据
        List<Menu> menus = (List<Menu>)valueOperations.get("menu_"+adminId);
        // 如果为空，从数据库查询
        if (CollectionUtils.isEmpty(menus)) {
            menus = menuMapper.getAdminByUserId(adminId);
            // 将数据存到redis中
            valueOperations.set("menu_"+adminId,menus);
        }
        return menus;
    }
    /**
     * 通过角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenuWithRole() {
        return menuMapper.getMenuWithRole();
    }
    /**
     * 查询所有菜单那
     * @return
     */
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
